<template>
  <div>
    <el-card style="width: 1300px;margin: 10px auto;" body-style="padding: 5px">
      <div slot="header" class="clearfix">
        <span style="line-height: 30px">项目名称：{{projectState.projectName}}</span>
        <div style="float: right;">
          <el-button
            class="filing-button"
            type="primary"
            icon="el-icon-plus"
            @click="addProduct"
          >添加商品</el-button>
          <el-button class="filing-button" type="primary" @click="downloadExcel">下载EXCEL模板</el-button>
          <el-upload
            style="display: inline; margin-left: 10px; margin-right: 10px;"
            :action="uploadExcel.url"
            :name="uploadExcel.name"
            accept=".xls, .xlsx"
            :on-success="uploadSuccess"
            :show-file-list="false"
          >
            <el-button class="filing-button" type="primary" slot="trigger">
              EXCEL导入
            </el-button>
          </el-upload>
          <el-button class="filing-button" type="primary" @click="clearAll" plain>清空所有</el-button>
        </div>
      </div>

      <div>

        <template v-if="tableDataObj.tableData&&tableDataObj.tableData.length>0">
          <table-list
            class="marTop"
            :tableObj="tableDataObj"
            :hasPagination="false"
            @showEditWindow="showEditWindow"
            @removeData="removeData"
          ></table-list>
        </template>
        <template v-else>
          <div class="empty">
            <div class="emptyIcon el-icon-document"></div>
            <div class="txt">暂无商品信息，请您在上方添加</div>
          </div>
        </template>
      </div>
    </el-card>
    <div style="text-align: center;">
      <el-button type="primary" @click="onSubmit">提交</el-button>
    </div>
    <GoodsForm
      v-if="isShow"
      :isTitle="isTitle"
      :isEditWindow="isEditWindow"
      @closedWindow="closed"
      @editData="onEditData"
    ></GoodsForm>
  </div>
</template>

<script>
import TableList from '@/components/goods/TableList.vue'
import { useProjectCustomerSetting } from '@/hooks/project'
import GoodsForm from '@/components/goods/form'
import { add } from '@/api/goodsReport'

export default {
  components: { TableList, GoodsForm },
  setup () {
    // const vm = getCurrentInstance()

    const { state: projectState } = useProjectCustomerSetting()

    return {
      projectState,
    }
  },
  data () {
    return {
      goodsList: [],
      isShow: false, // 显示添加商品时窗口
      isTitle: false, // 展示是 添加商品 还时编辑商品的标题
      isEditWindow: {
        isEditNum: 0, // 要编辑的商品序号
        isEditId: 0, // 要编辑的商品id
        data: null,
      },
      uploadExcel: {
        url: '/api/utils/formatGoodsReportExcelInfo',
        name: 'excel',
      },
    }
  },

  computed: {
    tableDataObj () {
      return {
        tableData: this.goodsList,
        isOperate: true, // 是否要操作按钮
        total: 0, // 总页数
        pageSize: 10, // 每页显示的条数
        pageNum: 1, // 默认第一页
        isShowPages: false, // 是否展示分页
      }
    },
  },

  methods: {
    onEditData (data) {
      if (this.isEditWindow.isEditNum > 0) {
        this.goodsList.splice(
          this.isEditWindow.isEditNum - 1,
          1,
          data,
        )
      } else {
        this.goodsList.push(data)
      }
    },
    // 添加商品
    addProduct () {
      this.isEditWindow.isEditNum = 0
      this.isShow = true
      this.isTitle = false
    },
    // 关闭弹窗
    closed (bl) {
      this.isShow = bl
      this.isEditWindow.isEditNum = 0
      this.isEditWindow.isEditId = 0
    },
    clearAll () {
      this.$confirm('确定清空所有信息吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        this.goodsList = []
      })
    },
    // 点击编辑 打开弹窗
    showEditWindow (obj) {
      this.isShow = true
      this.isTitle = true
      this.isEditWindow.isEditNum = obj.proNum
      this.isEditWindow.isEditId = obj.editId
      this.isEditWindow.data = this.goodsList[
        obj.proNum - 1
      ]
    },
    // 点击删除
    removeData (obj) {
      const index = this.goodsList.indexOf(obj)
      if (index > -1) {
        this.goodsList.splice(index, 1)
      }
    },

    downloadExcel () {
      window.location.href =
        'https://oss.tlwok.com/%E6%9C%8D%E5%8A%A1%E5%95%86-%E6%96%B0%E5%A2%9E%E6%89%B9%E9%87%8F%E5%95%86%E5%93%81.xlsx'
    },

    uploadSuccess (res, file, fileList) {
      const keys = [
        'categoryName',
        'brandName',
        'goodsName',
        'model',
        'num',
        'unit',
        'weight',
        'salesPrice',
        'spec',
        'packingList',
        'packageSize',
        'energySavingInfo',
        'environmenttalInfo',
        'place',
        'manufacturer',
        'refLink',
        'remark',
        'refImgs',
        'itemBarcode',
      ]
      if (res.success) {
        console.log(res.result)
        this.$message({
          type: 'success',
          message: res.desc,
        })
        res.result.forEach((item) => {
          const data = {}
          keys.forEach((key) => {
            data[key] = item[key]
          })
          data.refImgs = data.refImgs ? data.refImgs : '[]'
          console.log('data', data)
          this.goodsList.push(data)
        })
      } else this.$message.error(res.desc)
    },
    async onSubmit () {
      if (!this.goodsList.length) {
        this.$message.error('请添加商品')
        return false
      }
      const data = []
      this.goodsList.forEach(goods => {
        data.push({
          ...goods,
          purchasePlatformId: this.projectState.projectId,
          purchasePlatformName: this.projectState.projectName,
        })
      })
      console.log('data', data, this.projectState)
      const loading = this.$loading()
      try {
        const result = await add(data)
        console.log(result)
        this.$router.replace('/customer/goods')
        this.$alert('您可在 "我的报备 - 商品报备" 中查看报备记录及状态', '提交报备成功', {
          confirmButtonText: '确定',
          type: 'success',
        })
      } catch (error) {
        console.log(error)
      } finally {
        loading.close()
      }
    },
  },
}
</script>
<style lang='less' scoped>

.empty {
  text-align: center;
  padding: 20px 0;
  .emptyIcon {
    font-size: 64px;
    color: #bbb;
  }
  .txt {
    font-size: 14px;
    color: #bbb;
    margin-top: 30px;
  }
}

.content {
  width: 1300px;
  margin: 10px auto;
  border: 1px solid #999;
  position: relative;
  padding: 50px 20px;
  min-height: 300px;
}
.productBox {
  margin: 0 -20px;
  .topBox {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    .leftBtn {
      display: flex;
      align-items: center;
    }
    .topBtn {
      display: flex;
      align-items: center;
      .filing-button {
        margin-right: 18px;
        height: 35px;
        padding: 0 20px;
        font-size: 14px;
      }
    }
    .clearTopBtn {
      margin-left: 42px;
    }
    .firstTop {
      margin-right: 60px;
    }
  }
  .marTop {
    margin-top: 40px;
  }
  .empty {
    margin-top: 50px;
    text-align: center;
    padding: 20px 0;
    border-top: 1px solid #bbb;
    .emptyIcon {
      font-size: 64px;
      color: #bbb;
    }
    .txt {
      font-size: 14px;
      color: #bbb;
      margin-top: 30px;
    }
  }
}
.upload-box {
  display: inline-block;
}
</style>
